package com.bst.base.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.bst.base.domain.BaseInter;
import com.bst.base.mapper.BaseInterMapper;
import com.bst.base.service.IBaseInterService;
import com.bst.base.vo.OutInterParamVO;
import com.bst.common.core.domain.AjaxResult;
import com.bst.common.core.text.Convert;
import com.bst.common.exception.base.BaseException;
import com.bst.common.exception.base.BaseRuntimeException;
import com.bst.common.utils.StringUtils;
import com.bst.framework.datasource.DynamicDataSource;
import com.bst.framework.util.DBUtil;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接口管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-03-23
 */
@Service("baseInterService")
public class BaseInterServiceImpl implements IBaseInterService 
{
    @Autowired
    private BaseInterMapper baseInterMapper;

    /**
     * 查询接口管理
     * 
     * @param idInter 接口管理主键
     * @return 接口管理
     */
    @Override
    public BaseInter selectBaseInterByIdInter(Long idInter)
    {
        return baseInterMapper.selectBaseInterByIdInter(idInter);
    }

    @Override
    public BaseInter selectBaseInterByCdInter(String cdInter) {
        BaseInter inter = new BaseInter();
        inter.setCd(cdInter);
        List<BaseInter> inters = selectBaseInterList(inter);
        return inters.size()==0?null:inters.get(0);
    }

    /**
     * 查询接口管理列表
     * 
     * @param baseInter 接口管理
     * @return 接口管理
     */
    @Override
    public List<BaseInter> selectBaseInterList(BaseInter baseInter)
    {
        return baseInterMapper.selectBaseInterList(baseInter);
    }

    /**
     * 新增接口管理
     * 
     * @param baseInter 接口管理
     * @return 结果
     */
    @Override
    public int insertBaseInter(BaseInter baseInter)
    {
        return baseInterMapper.insertBaseInter(baseInter);
    }

    /**
     * 修改接口管理
     * 
     * @param baseInter 接口管理
     * @return 结果
     */
    @Override
    public int updateBaseInter(BaseInter baseInter)
    {
        return baseInterMapper.updateBaseInter(baseInter);
    }

    /**
     * 批量删除接口管理
     * 
     * @param idInters 需要删除的接口管理主键
     * @return 结果
     */
    @Override
    public int deleteBaseInterByIdInters(String idInters)
    {
        return baseInterMapper.deleteBaseInterByIdInters(Convert.toStrArray(idInters));
    }

    /**
     * 删除接口管理信息
     * 
     * @param idInter 接口管理主键
     * @return 结果
     */
    @Override
    public int deleteBaseInterByIdInter(Long idInter)
    {
        return baseInterMapper.deleteBaseInterByIdInter(idInter);
    }

    @Override
    public List<BaseInter> selectBaseInterByNoUser(Long idUserOuter) {
        return baseInterMapper.selectBaseInterByNoUser(idUserOuter);
    }

    @Override
    public List<BaseInter> selectBaseInterByAtUser(Long idUserOuter) {
        return baseInterMapper.selectBaseInterByAtUser(idUserOuter);
    }

    @Override
    public List<Map<String,Object>> queryByIdDb(Long idDb,String sql) throws BaseException {
        DruidDataSource datasource = (DruidDataSource)DynamicDataSource.getDataSourceMap().get(idDb+"");
        Connection connection=null;Statement st=null;ResultSet rs=null;
        try {
            connection = datasource.getConnection();
            st=(Statement) connection.createStatement();
            rs = st.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();
            int count = rsmd.getColumnCount();// 获取列的数量
            List<Map<String,Object>> dataList = new ArrayList<>();
            Map<String,Object> rowData;
            while (rs.next()) {
                rowData = new HashMap<>();
                for (int i = 1; i <= count; i++) {
                    rowData.put(rsmd.getColumnLabel(i),rs.getString(i));
                }
                dataList.add(rowData);
            }

            return dataList;
        }catch (Exception e) {
            throw new BaseException("查询错误"+e.getMessage());
        } finally {
            try {
                if(rs!=null && !rs.isClosed()) {
                    rs.close();
                }
                if(st!=null && !st.isClosed()) {
                    st.close();
                }
                if(connection!=null && !connection.isClosed()) {
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    @Override
    public AjaxResult interPreview(OutInterParamVO paramVO) {
        Long idInter = paramVO.getIdInter();
        String unique = paramVO.getUnique();
        String cdInter = paramVO.getCdInter();
        BaseInter inter=null;
        if(idInter!=null) {
            inter = this.selectBaseInterByIdInter(idInter);
        } else if(StringUtils.isNotEmpty(unique)) {
            BaseInter model = new BaseInter();
            model.setSignUnique(unique);
            List<BaseInter> inters = baseInterMapper.selectBaseInterList(model);
            if(inters.size()>0) {
                inter = inters.get(0);
            }
        } else if(StringUtils.isNotEmpty(cdInter)) {
            BaseInter model = new BaseInter();
            model.setCd(cdInter);
            List<BaseInter> inters = baseInterMapper.selectBaseInterList(model);
            if(inters.size()>0) {
                inter = inters.get(0);
            }
        }
        if(inter==null) {
            return AjaxResult.error("接口号错误");
        }
        String sql = inter.getSqlQry();
        List<String> sqlParamNames = DBUtil.getParamFromSql(sql);
        Map<String,String> param = paramVO.getParam();
        if(param!=null) {
            for(Map.Entry<String,String> entry:paramVO.getParam().entrySet()) {
                sqlParamNames.remove(entry.getKey());
                sql = sql.replaceAll("\\$\\{"+entry.getKey()+"\\}",entry.getValue());
            }
            if(sqlParamNames.size()>0) {
                return AjaxResult.error("参数缺少："+sqlParamNames.toString());
            }
        }
        //根据数据源提取数据
        try {
            List<Map<String,Object>> data = this.queryByIdDb(inter.getIdDb(), StringEscapeUtils.unescapeHtml4(sql));
            return AjaxResult.success(data);
        } catch (BaseException e) {
            throw new BaseRuntimeException(e.getMessage());
        }
    }

    @Override
    public List<Map<String, Object>> interPreview2(OutInterParamVO paramVO) {
        AjaxResult result = this.interPreview(paramVO);
        if(AjaxResult.isSuccess(result)) {
            return (List<Map<String, Object>>)result.get(AjaxResult.DATA_TAG);
        } else {
            throw new BaseRuntimeException("接口"+paramVO.getCdInter()+"异常");
        }
    }

    @Override
    public List<Map<String, Object>> interPreview2(String cdInter) {
        AjaxResult result = this.interPreview(new OutInterParamVO(cdInter));
        if(AjaxResult.isSuccess(result)) {
            return (List<Map<String, Object>>)result.get(AjaxResult.DATA_TAG);
        } else {
            throw new BaseRuntimeException("接口"+cdInter+"异常");
        }
    }
}
